package com.sk.weichat.ui.contacts;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.GroupMessageAdapter;
import com.sk.weichat.adapter.MultipleGroupMessageItem;
import com.sk.weichat.adapter.MyMultipleItem;
import com.sk.weichat.adapter.NewFriendAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.GroupMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.GroupMessageDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.groupchat.GroupManageActivity;
import com.sk.weichat.ui.groupchat.JoinGroupApplyActivity;
import com.sk.weichat.ui.groupchat.OpenGroupInfoActivity;
import com.sk.weichat.ui.groupchat.RefuseGroupApplyActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.multi.InviteVerifyActivity;
import com.sk.weichat.ui.message.multi.RoomInfoActivity;
import com.sk.weichat.ui.nearby.UserListGatherActivity;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.sk.weichat.xmpp.listener.NewFriendListener;
import com.swipemenulib.SwipeMenuLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 群通知列表
 * create by swy 2019-09-20
 */
public class GroupMessageActivity extends BaseActivity {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView mPullToRefreshListView;
    private GroupMessageAdapter mAdapter;
    private List<GroupMessage> mGroupMessageList;
    private List<MultipleGroupMessageItem> mItemList;
    private String mLoginUserId;
    private LinearLayout linearEmpty;
    private TextView tvSearchFriend;
    private Handler mHandler = new Handler();
//    private TextView mTvRight;
    private ImageView iv_title_right;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_pullrefresh_list);
        mLoginUserId = coreManager.getSelf().getUserId();
        mGroupMessageList = new ArrayList<>();
        mItemList = new ArrayList<>();
        initActionBar();
        initView();
    }

    private void initActionBar() {
        getSupportActionBar().hide();

        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.message_group_notification));

        iv_title_right = findViewById(R.id.iv_title_right);

        iv_title_right.setImageDrawable(getResources().getDrawable(R.mipmap.icon_clear_big));

//        mTvRight = (TextView) findViewById(R.id.tv_title_right);
//        mTvRight.setTextColor(ContextCompat.getColor(this,R.color.deep_purple));
//        mTvRight.setText("清空");

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.iv_title_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showClearUnReadDialog();

            }
        });

    }

    /**
     * 清除关系通知弹框
     */
    private void showClearUnReadDialog() {

        SelectionFrame mSF = new SelectionFrame(this);
        mSF.setSomething(getString(R.string.dialog_title), getString(R.string.msg_clear_group), new SelectionFrame.OnSelectionFrameClickListener() {
            @Override
            public void cancelClick() {

            }

            @Override
            public void confirmClick() {
                GroupMessageDao.getInstance().removeAllGroupMsg(mLoginUserId);
                mGroupMessageList.clear();
                mItemList.clear();
                mAdapter.notifyDataSetChanged();
                linearEmpty.setVisibility(View.VISIBLE);
                iv_title_right.setVisibility(View.GONE);
                MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());
            }
        });
        mSF.show();
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    private void initView() {
        linearEmpty = findViewById(R.id.linear_empty_tips);
        tvSearchFriend = findViewById(R.id.tv_search_friend);
        tvSearchFriend.setText("暂无群通知");
        tvSearchFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(GroupMessageActivity.this, UserListGatherActivity.class));
            }
        });
        mPullToRefreshListView = findViewById(R.id.pull_refresh_list);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mPullToRefreshListView.setLayoutManager(manager);
        mAdapter = new GroupMessageAdapter(this, mItemList );
        mAdapter.setHasStableIds(true);
        mPullToRefreshListView.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) mPullToRefreshListView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //侧滑删除单个item
                if (view.getId()==R.id.delete_tv){
                    GroupMessageDao.getInstance().removeGroupMsg(mLoginUserId,mGroupMessageList.get(position).getPacketId());
                    mGroupMessageList.remove(position);
                    mItemList.remove(position);

                    if(mGroupMessageList.size()==0){
                        linearEmpty.setVisibility(View.VISIBLE);
                        iv_title_right.setVisibility(View.GONE);
                    }
                    adapter.notifyItemRemoved(position + 1);
                    adapter.notifyItemRangeChanged(position, mItemList.size() - (position + 1));
                    ((SwipeMenuLayout) view.getParent()).quickClose();
                    MsgBroadcast.broadcastMsgUiUpdate(getApplicationContext());

                }else if (view.getId()==R.id.layout_group_message_item){//点击item跳转
                    clickItemForGroupMessageState(mGroupMessageList.get(position));

                }else if (view.getId()==R.id.avatar_img){//点击头像跳转
                    clickItemForAvatar(mGroupMessageList.get(position));
                }
            }
        });

        refreshLayout  = findViewById(R.id.refresh_search_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    /**
     * 请求公共消息
     * <p>
     * 是下拉刷新，还是上拉加载
     */
    private void loadData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                long startTime = System.currentTimeMillis();
                final List<GroupMessage> groupMessageList = GroupMessageDao.getInstance().getAllGroupMsg(mLoginUserId);
                // 保证至少200ms的刷新过程
                long delayTime = 200 - (startTime - System.currentTimeMillis());
                if (delayTime < 0) {
                    delayTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mGroupMessageList.clear();
                        mItemList.clear();
                        if (groupMessageList != null && groupMessageList.size() > 0) {
                            mGroupMessageList.addAll(groupMessageList);
                        }
                        if (mGroupMessageList != null && mGroupMessageList.size() > 0){
                            linearEmpty.setVisibility(View.GONE);
                        }else {
                            linearEmpty.setVisibility(View.VISIBLE);
                            iv_title_right.setVisibility(View.GONE);
                        }

                        for (int i = 0; i < groupMessageList.size(); i++) {
                            if (!TextUtils.isEmpty(groupMessageList.get(i).getHandler())&&!TextUtils.isEmpty(groupMessageList.get(i).getReason())) {//显示四行
                                mItemList.add(new MultipleGroupMessageItem(MultipleGroupMessageItem.ITEM_ROW_FOUR, groupMessageList.get(i)));//添加群消息item
                            } else {
                                mItemList.add(new MultipleGroupMessageItem(MultipleGroupMessageItem.ITEM_ROW_THREE, groupMessageList.get(i)));//添加群消息item
                            }

                        }
                        mAdapter.notifyDataSetChanged();
                        refreshLayout.finishRefresh();
                    }
                }, delayTime);
            }
        }).start();

    }

    /**
     * 点击适配器item头像跳转
     * @param groupMessage
     */
    private void clickItemForAvatar(GroupMessage groupMessage) {
        Intent intent;
        switch (groupMessage.getState()) {
            case GroupMessage.STATUS_GM_10://设置管理员
            case GroupMessage.STATUS_GM_11://取消管理员
            case GroupMessage.STATUS_GM_15://其他人被踢出群
            case GroupMessage.STATUS_GM_18://转让群主给你
            case GroupMessage.STATUS_GM_19://转让群主给你他人
            case GroupMessage.STATUS_GM_20://你的邀请被拒绝
                intent = new Intent(mContext, RoomInfoActivity.class);
                //Log.e("lzs", "进入群信息:" + mUseId);
                intent.putExtra(AppConstant.EXTRA_USER_ID, groupMessage.getUserId());
                intent.putExtra(AppConstant.EXTRA_IS_GROUP_CHAT, true);
                mContext.startActivity(intent);
                break;
            case GroupMessage.STATUS_GM_12://你退出群
            case GroupMessage.STATUS_GM_13: //你被移出群
            case GroupMessage.STATUS_GM_21://你的申请被拒绝
                startActivity(new Intent(mContext, OpenGroupInfoActivity.class)
                        .putExtra("RoomId", groupMessage.getRoomId())
                .putExtra("packetId",groupMessage.getPacketId()));
                break;
            case GroupMessage.STATUS_GM_14://其他人退出群
                intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, groupMessage.getToUserId());
                mContext.startActivity(intent);
                break;
            case GroupMessage.STATUS_GM_16://邀请进群
            case GroupMessage.STATUS_GM_17://申请进群
                intent = new Intent(mContext, PersonalCenterActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, groupMessage.getFromUserId());
                mContext.startActivity(intent);
                break;
        }
    }

    private void clickItemForGroupMessageState( GroupMessage groupMessage) {
        switch (groupMessage.getState()) {
            case GroupMessage.STATUS_GM_10://设置管理员
            case GroupMessage.STATUS_GM_11://取消管理员
            case GroupMessage.STATUS_GM_12://你退出群
            case GroupMessage.STATUS_GM_13: //你被移出群
            case GroupMessage.STATUS_GM_14://其他人退出群
            case GroupMessage.STATUS_GM_15://其他人被踢出群
            case GroupMessage.STATUS_GM_18://转让群主给你
            case GroupMessage.STATUS_GM_19://转让群主给你他人
                clickManagerSetItem(groupMessage);
                break;

            case GroupMessage.STATUS_GM_16://邀请进群
                clickInviteItem(groupMessage);
                break;

            case GroupMessage.STATUS_GM_17://申请进群
                clickApplyItem(groupMessage);
                break;
            case GroupMessage.STATUS_GM_20://你的邀请被拒绝
            case GroupMessage.STATUS_GM_21://你的申请被拒绝
                clickRefuseApplyItem(groupMessage);
                break;
        }

    }

    /**
     * 点击适配器item跳转
     * @param groupMessage
     */
    private void clickManagerSetItem(GroupMessage groupMessage) {
        Intent intent = new Intent(mContext, GroupManagerSetActivity.class);
        intent.putExtra("VERIFY_MESSAGE_PACKET", groupMessage.getPacketId());
        mContext.startActivity(intent);
    }

    private void clickInviteItem(GroupMessage groupMessage) {
        Intent intent = new Intent(mContext, InviteVerifyActivity.class);
        intent.putExtra("VERIFY_MESSAGE_FRIEND_ID", groupMessage.getUserId());
        intent.putExtra("VERIFY_MESSAGE_PACKET", groupMessage.getPacketId());
        intent.putExtra("VERIFY_MESSAGE_ROOM_ID", groupMessage.getRoomId());
        intent.putExtra("VERIFY_MESSAGE_INVITE_ID", groupMessage.getFromUserId());
        mContext.startActivity(intent);
    }

    private void clickApplyItem(GroupMessage groupMessage) {
        Intent intent = new Intent(mContext, JoinGroupApplyActivity.class);
        intent.putExtra("msgId", groupMessage.getPacketId());
        mContext.startActivity(intent);
    }

    private void clickRefuseApplyItem(GroupMessage groupMessage) {
        Intent intent = new Intent(mContext, RefuseGroupApplyActivity.class);
        intent.putExtra("msgId", groupMessage.getPacketId());
        mContext.startActivity(intent);
    }

}
